package com.hightrast.service.converToClassMapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.hightrast.service.api.domain.bo.QueryShopifyOrderProductItems;
import com.hightrast.service.api.domain.bo.QueryShopifyOrders;
import com.hightrast.service.api.entity.RastOrderProductItems;
import com.hightrast.service.api.entity.RastOrderProductRefundItems;
import com.hightrast.service.api.entity.RastOrders;
import com.hightrast.service.api.enums.RefundStatusEnum;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Mapper
public interface OrderMapper {
    OrderMapper INSTANCE = Mappers.getMapper(OrderMapper.class);

    @Mapping(source = "closed_at", target = "closedAt")
    @Mapping(source = "created_at", target = "createdAt")
    @Mapping(source = "updated_at", target = "updatedAt")
    @Mapping(source = "test", target = "test")
    @Mapping(source = "total_price", target = "totalPrice")
    @Mapping(source = "subtotal_price", target = "subtotalPrice")
    @Mapping(source = "total_weight", target = "totalWeight")
    @Mapping(source = "total_tax", target = "totalTax")
    @Mapping(source = "taxes_included", target = "taxesIncluded")
    @Mapping(source = "financial_status", target = "financialStatus")
    @Mapping(source = "confirmed", target = "confirmed")
    @Mapping(source = "total_discounts", target = "totalDiscounts")
    @Mapping(source = "totalLine_items_price", target = "totalLineItemsPrice")
    @Mapping(source = "buyer_accepts_marketing", target = "buyerAcceptsMarketing")
    @Mapping(source = "order_number", target = "orderNumber")
    @Mapping(source = "source_name", target = "sourceName")
    @Mapping(source = "order_status_url", target = "orderStatusUrl")
    @Mapping(source = "presentment_currency", target = "presentmentCurrency")
    @Mapping(source = "admin_graphql_api_id", target = "adminGraphqlApiId")
    @Mapping(source = "current_total_price", target = "currentTotalPrice")
    @Mapping(source = "total_outstanding", target = "totalOutstanding")
    @Mapping(source = "current_subtotal_price", target = "currentSubtotalPrice")
    @Mapping(source = "current_total_tax", target = "currentTotalTax")
    @Mapping(source = "current_total_discounts", target = "currentTotalDiscounts")
    @Mapping(source = "fulfillment_status", target = "fulfillmentStatus")
    @Mapping(source = "line_items", target = "lineItems")
    @Mapping(source = "refunds", target = "refundItems")
    RastOrders queryShopifyToOrder(QueryShopifyOrders queryShopifyOrders);

    // 自定义方法：将 OffsetDateTime 转换为 LocalDateTime
    default LocalDateTime convertDateTime(OffsetDateTime offsetDateTime) {
        return offsetDateTime != null ? offsetDateTime.toLocalDateTime() : null;
    }

    // 商品项转换
    default List<RastOrderProductItems> convertLineItems(List<QueryShopifyOrderProductItems> queryShopifyOrderProductItems) {
        if (queryShopifyOrderProductItems == null) {
            return new ArrayList<>();
        }
        return queryShopifyOrderProductItems.stream()
                .map(this::convertToRastOrderProductItems) // 自定义转换逻辑
                .collect(Collectors.toList());
    }

    default RastOrderProductItems convertToRastOrderProductItems(QueryShopifyOrderProductItems item) {
        // 在这里进行属性转换
        RastOrderProductItems rastItem = BeanUtil.copyProperties(item, RastOrderProductItems.class);
        rastItem.setOrderId(item.getOrder_id());
        rastItem.setVariantId(item.getVariant_id());
        rastItem.setVariantTitle(item.getVariant_title());
        rastItem.setFulfillmentService(item.getFulfillment_service());
        rastItem.setProductId(item.getProduct_id());
        rastItem.setRequiresShipping(convertBoolean(item.getRequires_shipping()));
        rastItem.setTaxable(convertBoolean(item.getTaxable()));
        rastItem.setGiftCard(convertBoolean(item.getGift_card()));
        rastItem.setVariantInventoryManagement(item.getVariant_inventory_management());
        rastItem.setProductExists(convertBoolean(item.getProduct_exists()));
        rastItem.setFulfillableQuantity(item.getFulfillable_quantity());
//        rastItem.setTotalDiscount(item.getTotal_discount());
        rastItem.setFulfillmentStatus(item.getFulfillment_status());
        rastItem.setPreTaxPrice(item.getPre_tax_price());
        // 设置 rastItem 的属性
        return rastItem;
    }

    // 退款商品项转换
    default List<RastOrderProductRefundItems> convertRefundLineItems(List<QueryShopifyOrders.refunds> refunds) {
        if (refunds == null) {
            return new ArrayList<>();
        }
        List<QueryShopifyOrders.refundsItem> refundsItems = refunds.stream().flatMap(re -> re.getRefund_line_items().parallelStream()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(refundsItems)){
            return new ArrayList<>();
        }
        List<QueryShopifyOrders.transactions> transactions = refunds.stream().flatMap(re -> re.getTransactions().parallelStream()).collect(Collectors.toList());
        return refundsItems.stream()
                .map(ri -> {
                    RastOrderProductRefundItems refundItems = new RastOrderProductRefundItems();
                    refundItems.setId(ri.getId());
                    refundItems.setLineItemId(ri.getLine_item_id());
                    refundItems.setQuantity(ri.getQuantity());
                    refundItems.setSubtotal(ri.getSubtotal());
                    // 只要有一个是空的，或者 只有有一个不等于成功就是退款中，否则就是退款成功
                    if(transactions.stream().anyMatch(ts -> StrUtil.isEmpty(ts.getStatus()))
                            || transactions.stream().anyMatch(ts -> !RefundStatusEnum.success.getDesc().equals(ts.getStatus()))){
                        refundItems.setStatus(RefundStatusEnum.pending.getDesc());
                    }else if(transactions.stream().allMatch(ts -> RefundStatusEnum.success.getDesc().equals(ts.getStatus()))){
                        refundItems.setStatus(RefundStatusEnum.success.getDesc());
                    }else {
                        refundItems.setStatus(RefundStatusEnum.pending.getDesc());
                    }
                    return refundItems;
                }) // 自定义转换逻辑
                .collect(Collectors.toList());
    }


    // 自定义转换方法：将 Boolean 转换为 Integer
    default Integer convertBoolean(Boolean value) {
        if(value == null){
            return null;
        }
        return value ? 1 : 0;
    }
}